package com.example.select_lesson;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.gc.materialdesign.views.ButtonRectangle;


public class MainActivity extends Activity {


    private EditText name;
    private EditText pw;
    private String text;
    private String password;
    private ButtonRectangle login;
    private ImageView go1;
    private Button mButton;
    private ImageView imageView;
    private TopSlidingLayout topSlidingLayout;
    private CheckBox rememberPassword;
    private CheckBox autoLogin;
    private SharedPreferences sp;

    private MyDataBaseHelper dbHelper;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.skyblue));
        }
        //用来记住密码
        sp = this.getSharedPreferences("userInfo", Context.MODE_APPEND);
        // 初始化控件
        init();
        //判断自动登陆选择框的状态
        if (sp.getBoolean("AUTOISCHECK", false)) {

            autoLogin.setChecked(true);
            rememberPassword.setChecked(true);
            String name = sp.getString("USER_NAME", "");
            HomeActivity.actionStart(getApplicationContext(), name);
        }
        //判断记住密码选择框的状态
        if (sp.getBoolean("ISCHECK", false)) {
            //设置默认是记录密码状态
            rememberPassword.setChecked(true);
            name.setText(sp.getString("USER_NAME", ""));
            pw.setText(sp.getString("PASSWORD", ""));
            if(sp.getBoolean("ISCHECK",true)) {
                //让记住密码，再次登陆时变色……
                login.setBackgroundColor(getResources().getColor(R.color.my_orange));
            }
        }

        //两个框框都有内容时改变颜色&提示输出帐号密码
        name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!name.getText().toString().equals("") && !pw.getText().toString().equals("")) {
                    login.setBackgroundColor(getResources().getColor(R.color.my_orange));
                } else if (!name.getText().toString().equals((""))) {
                    login.setBackgroundColor(getResources().getColor(R.color.skyblue));
                } else {
                    login.setBackgroundColor(getResources().getColor(R.color.skyblue));
                }
            }
        });

        pw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!name.getText().toString().equals("") && !pw.getText().toString().equals("")) {
                    login.setBackgroundColor(getResources().getColor(R.color.my_orange));
                } else if (!name.getText().toString().equals((""))) {
                    login.setBackgroundColor(getResources().getColor(R.color.skyblue));
                } else {
                    login.setBackgroundColor(getResources().getColor(R.color.skyblue));
                }
            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text = name.getText().toString();
                password = pw.getText().toString();
                /**
                 *从数据库中获得该学号学生的密码、判断是否相等
                 */
                int tempPW = 0;
                dbHelper = new MyDataBaseHelper(getApplicationContext(), "StudentManager.db", null, 1);
                dbHelper.getWritableDatabase();
                db = dbHelper.getWritableDatabase();
                Cursor cursor = db.rawQuery("select * from Student where studentId=?",
                        new String[] {text});
                if (cursor.moveToFirst()) {
                    do {
                        tempPW = cursor.getInt(cursor.getColumnIndex("password"));
                    } while (cursor.moveToNext());
                }
                cursor.close();
                if (password.equals(tempPW + "")) {
                    //登录成功和记住密码框为选中状态才保存用户信息
                    if (rememberPassword.isChecked()) {
                        //记住用户名、密码、
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("USER_NAME", text);
                        editor.putString("PASSWORD", password);
                        editor.commit();
                    }
                    /**
                     * 这里做跳转！
                     */
                    HomeActivity.actionStart(getApplicationContext(), text);
                } else if (text.equals("")) {
                    Toast.makeText(MainActivity.this, "学号不能为空", Toast.LENGTH_SHORT).show();
                } else if (password.equals("")) {
                    Toast.makeText(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "学号/密码错误！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        autoLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (autoLogin.isChecked()) {
                    sp.edit().putBoolean("AUTOISCHECK", true).commit();
                    rememberPassword.setChecked(true);
                } else {
                    sp.edit().putBoolean("AUTOISCHECK", false).commit();
                }
            }
        });

        //监听记住密码多选框按钮事件
        rememberPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(rememberPassword.isChecked()) {
                    sp.edit().putBoolean("ISCHECK", true).commit();
                }else {
                    sp.edit().putBoolean("ISCHECK", false).commit();
                }
            }
        });

        //给这些显示在主页面上的控件添加滑动事件
        topSlidingLayout.setScrollEvent(go1);
        topSlidingLayout.setScrollEvent(imageView);
        topSlidingLayout.setScrollEvent(mButton);

        //按钮跳转
        go1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (topSlidingLayout.isTopLayoutVisible()) {
                    topSlidingLayout.scrollToContentFromTopMenu();
                } else {
                    topSlidingLayout.initShowTopState();
                    topSlidingLayout.scrollToTopMenu();

                    //让其跳转后焦点转移到editText
                    if (name.getText().toString().equals("")) {
                        name.requestFocus();
                    } else if (pw.getText().toString().equals("")) {
                        pw.requestFocus();
                    }
                }
            }
        });

    }

    private void init() {
        rememberPassword = (CheckBox) findViewById(R.id.cb_password);
        autoLogin = (CheckBox) findViewById(R.id.cb_login);

        //下滑登陆菜单
        topSlidingLayout = (TopSlidingLayout) findViewById(R.id.top_sliding_layout);
        //Go跳转按钮
        go1 = (ImageView) findViewById(R.id.iv_go);
        //为了获取到下滑的滑动事件实例化
        mButton = (Button) findViewById(R.id.bt_content);
        imageView = (ImageView) findViewById(R.id.iv_content);

        name = (EditText) findViewById(R.id.et_name);
        pw = (EditText) findViewById(R.id.et_pass_word);
        login = (ButtonRectangle) findViewById(R.id.bt_go);

        //让帐号密码只能输入数字
        name.setInputType(InputType.TYPE_CLASS_NUMBER);
        pw.setInputType(InputType.TYPE_CLASS_NUMBER);
        //隐藏密码
        pw.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }


    @Override
    protected void onStop() {
        super.onStop();
        finish();
    }
}
